<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Netty聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #chatContainer {
            border: 1px solid #ccc;
            height: 400px;
            overflow-y: scroll;
            padding: 10px;
            margin-bottom: 10px;
            background-color: #f9f9f9;
        }
        #messageInput {
            width: 70%;
            padding: 10px;
        }
        #sendButton {
            width: 25%;
            padding: 10px;
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        .message {
            margin-bottom: 10px;
            padding: 5px;
            border-radius: 5px;
        }
        .system-message {
            background-color: #e9ecef;
            text-align: center;
            font-style: italic;
        }
        .user-message {
            background-color: #d1ecf1;
        }
        .self-message {
            background-color: #d4edda;
            text-align: right;
        }
    </style>
</head>
<body>
    <h1>Netty聊天室</h1>
    <div>
        <label for="userId">用户ID:</label>
        <input type="text" id="userId" placeholder="请输入用户ID">
        <button id="joinButton">加入聊天</button>
        <button id="leaveButton" disabled>离开聊天</button>
    </div>
    <br>
    <div id="chatContainer"></div>
    <div>
        <input type="text" id="messageInput" placeholder="输入消息..." disabled>
        <button id="sendButton" disabled>发送</button>
    </div>

    <script>
        let ws = null;
        let currentUserId = null;
        
        document.getElementById('joinButton').addEventListener('click', joinChat);
        document.getElementById('leaveButton').addEventListener('click', leaveChat);
        document.getElementById('sendButton').addEventListener('click', sendMessage);
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        function joinChat() {
            const userId = document.getElementById('userId').value;
            if (!userId) {
                alert('请输入用户ID');
                return;
            }
            
            currentUserId = userId;
            
            // 连接到WebSocket服务器
            const wsUrl = 'ws://localhost:8090/ws';
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                console.log('连接已建立');
                // 发送加入消息
                const joinMessage = {
                    type: 'JOIN',
                    sender: userId,
                    content: userId + ' 加入了聊天'
                };
                ws.send(JSON.stringify(joinMessage));
                
                // 更新UI状态
                document.getElementById('userId').disabled = true;
                document.getElementById('joinButton').disabled = true;
                document.getElementById('leaveButton').disabled = false;
                document.getElementById('messageInput').disabled = false;
                document.getElementById('sendButton').disabled = false;
            };
            
            ws.onmessage = function(event) {
                const message = JSON.parse(event.data);
                displayMessage(message);
            };
            
            ws.onclose = function() {
                console.log('连接已关闭');
                // 处理断线重连
                handleDisconnect();
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
            };
        }
        
        function leaveChat() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                const leaveMessage = {
                    type: 'LEAVE',
                    sender: currentUserId,
                    content: currentUserId + ' 离开了聊天'
                };
                ws.send(JSON.stringify(leaveMessage));
                ws.close();
            }
            
            // 更新UI状态
            document.getElementById('userId').disabled = false;
            document.getElementById('joinButton').disabled = false;
            document.getElementById('leaveButton').disabled = true;
            document.getElementById('messageInput').disabled = true;
            document.getElementById('sendButton').disabled = true;
        }
        
        function sendMessage() {
            const content = document.getElementById('messageInput').value;
            if (!content.trim() || !ws || ws.readyState !== WebSocket.OPEN) {
                return;
            }
            
            const message = {
                type: 'CHAT',
                sender: currentUserId,
                content: content,
                timestamp: new Date().toISOString()
            };
            
            ws.send(JSON.stringify(message));
            document.getElementById('messageInput').value = '';
        }
        
        function displayMessage(message) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            
            // 根据消息类型设置样式
            if (message.type === 'SYSTEM') {
                messageDiv.className = 'message system-message';
                messageDiv.innerHTML = `<strong>${message.content}</strong>`;
            } else {
                const isSelf = message.sender === currentUserId;
                messageDiv.className = `message ${isSelf ? 'self-message' : 'user-message'}`;
                messageDiv.innerHTML = `
                    <strong>${message.sender}</strong>: ${message.content}
                    <br><small>${message.timestamp}</small>
                `;
            }
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        function handleDisconnect() {
            // 显示断线提示
            const disconnectMessage = {
                type: 'SYSTEM',
                content: '连接已断开，正在尝试重新连接...',
                timestamp: new Date().toISOString()
            };
            displayMessage(disconnectMessage);
            
            // 尝试重新连接
            setTimeout(function() {
                joinChat();
            }, 3000);
        }
    </script>
</body>
</html>